package edu.sdjzu.exam.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import edu.sdjzu.exam.common.CommonResponse;
import edu.sdjzu.exam.domain.auth.Permission;
import edu.sdjzu.exam.domain.auth.Role;
import edu.sdjzu.exam.domain.auth.User;
import edu.sdjzu.exam.service.rbac.RbacService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/rbac")
@SaCheckRole(value = {"teacher", "super_admin"}, mode = cn.dev33.satoken.annotation.SaMode.OR)
public class RbacController {

    @Autowired
    private RbacService rbacService;

    // 用户管理
    @GetMapping("/users")
    public CommonResponse<List<User>> getUsers() {
        try {
            List<User> users = rbacService.getAllUsers();
            return CommonResponse.success(users);
        } catch (Exception e) {
            return CommonResponse.error("获取用户列表失败：" + e.getMessage());
        }
    }

    @PostMapping("/users")
    public CommonResponse<User> createUser(@RequestBody User user) {
        try {
            User createdUser = rbacService.createUser(user);
            return CommonResponse.success("用户创建成功", createdUser);
        } catch (Exception e) {
            return CommonResponse.error("创建用户失败：" + e.getMessage());
        }
    }

    @GetMapping("/users/{userId}")
    public CommonResponse<User> getUser(@PathVariable Long userId) {
        try {
            User user = rbacService.findUserById(userId);
            return CommonResponse.success(user);
        } catch (Exception e) {
            return CommonResponse.error("获取用户失败：" + e.getMessage());
        }
    }
    
    @GetMapping("/users/by-username/{username}")
    public CommonResponse<User> getUserByUsername(@PathVariable String username) {
        try {
            User user = rbacService.findUserByUsername(username);
            if (user == null) {
                return CommonResponse.error("用户不存在");
            }
            return CommonResponse.success(user);
        } catch (Exception e) {
            return CommonResponse.error("获取用户失败：" + e.getMessage());
        }
    }

    @PutMapping("/users/{userId}")
    public CommonResponse<String> updateUser(@PathVariable Long userId, @RequestBody User user) {
        try {
            user.setUserId(userId);
            rbacService.updateUser(user);
            return CommonResponse.success("用户更新成功");
        } catch (Exception e) {
            return CommonResponse.error("更新用户失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/users/{userId}")
    public CommonResponse<String> deleteUser(@PathVariable Long userId) {
        try {
            rbacService.deleteUser(userId);
            return CommonResponse.success("用户删除成功");
        } catch (Exception e) {
            return CommonResponse.error("删除用户失败：" + e.getMessage());
        }
    }

    // 角色管理
    @GetMapping("/roles")
    public CommonResponse<List<Role>> getRoles() {
        try {
            List<Role> roles = rbacService.getAllRoles();
            return CommonResponse.success(roles);
        } catch (Exception e) {
            return CommonResponse.error("获取角色列表失败：" + e.getMessage());
        }
    }

    @PostMapping("/roles")
    public CommonResponse<Role> createRole(@RequestBody Role role) {
        try {
            Role createdRole = rbacService.createRole(role);
            return CommonResponse.success("角色创建成功", createdRole);
        } catch (Exception e) {
            return CommonResponse.error("创建角色失败：" + e.getMessage());
        }
    }

    @GetMapping("/roles/{roleId}")
    public CommonResponse<Role> getRole(@PathVariable Long roleId) {
        try {
            Role role = rbacService.findRoleById(roleId);
            return CommonResponse.success(role);
        } catch (Exception e) {
            return CommonResponse.error("获取角色失败：" + e.getMessage());
        }
    }

    @PutMapping("/roles/{roleId}")
    public CommonResponse<String> updateRole(@PathVariable Long roleId, @RequestBody Role role) {
        try {
            role.setRoleId(roleId);
            rbacService.updateRole(role);
            return CommonResponse.success("角色更新成功");
        } catch (Exception e) {
            return CommonResponse.error("更新角色失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/roles/{roleId}")
    public CommonResponse<String> deleteRole(@PathVariable Long roleId) {
        try {
            rbacService.deleteRole(roleId);
            return CommonResponse.success("角色删除成功");
        } catch (Exception e) {
            return CommonResponse.error("删除角色失败：" + e.getMessage());
        }
    }

    // 权限管理
    @GetMapping("/permissions")
    public CommonResponse<List<Permission>> getPermissions() {
        try {
            List<Permission> permissions = rbacService.getAllPermissions();
            return CommonResponse.success(permissions);
        } catch (Exception e) {
            return CommonResponse.error("获取权限列表失败：" + e.getMessage());
        }
    }

    @PostMapping("/permissions")
    public CommonResponse<Permission> createPermission(@RequestBody Permission permission) {
        try {
            Permission createdPermission = rbacService.createPermission(permission);
            return CommonResponse.success("权限创建成功", createdPermission);
        } catch (Exception e) {
            return CommonResponse.error("创建权限失败：" + e.getMessage());
        }
    }

    @GetMapping("/permissions/{permissionId}")
    public CommonResponse<Permission> getPermission(@PathVariable Long permissionId) {
        try {
            Permission permission = rbacService.findPermissionById(permissionId);
            return CommonResponse.success(permission);
        } catch (Exception e) {
            return CommonResponse.error("获取权限失败：" + e.getMessage());
        }
    }

    @PutMapping("/permissions/{permissionId}")
    public CommonResponse<String> updatePermission(@PathVariable Long permissionId, @RequestBody Permission permission) {
        try {
            permission.setPermissionId(permissionId);
            rbacService.updatePermission(permission);
            return CommonResponse.success("权限更新成功");
        } catch (Exception e) {
            return CommonResponse.error("更新权限失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/permissions/{permissionId}")
    public CommonResponse<String> deletePermission(@PathVariable Long permissionId) {
        try {
            rbacService.deletePermission(permissionId);
            return CommonResponse.success("权限删除成功");
        } catch (Exception e) {
            return CommonResponse.error("删除权限失败：" + e.getMessage());
        }
    }

    // 用户角色关联
    @PostMapping("/users/{userId}/roles/{roleId}")
    public CommonResponse<String> assignRoleToUser(@PathVariable Long userId, @PathVariable Long roleId) {
        try {
            rbacService.assignRoleToUser(userId, roleId);
            return CommonResponse.success("角色分配成功");
        } catch (Exception e) {
            return CommonResponse.error("分配角色失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/users/{userId}/roles/{roleId}")
    public CommonResponse<String> removeRoleFromUser(@PathVariable Long userId, @PathVariable Long roleId) {
        try {
            rbacService.removeRoleFromUser(userId, roleId);
            return CommonResponse.success("角色移除成功");
        } catch (Exception e) {
            return CommonResponse.error("移除角色失败：" + e.getMessage());
        }
    }

    @GetMapping("/users/{userId}/roles")
    public CommonResponse<List<Role>> getUserRoles(@PathVariable Long userId) {
        try {
            List<Role> roles = rbacService.getUserRoles(userId);
            return CommonResponse.success(roles);
        } catch (Exception e) {
            return CommonResponse.error("获取用户角色失败：" + e.getMessage());
        }
    }
    
    @GetMapping("/roles/{roleId}/users")
    public CommonResponse<List<User>> getUsersByRole(@PathVariable Long roleId) {
        try {
            List<User> users = rbacService.findUsersByRoleId(roleId);
            return CommonResponse.success(users);
        } catch (Exception e) {
            return CommonResponse.error("获取角色用户失败：" + e.getMessage());
        }
    }
    
    @GetMapping("/roles/by-name/{roleName}/users")
    public CommonResponse<List<User>> getUsersByRoleName(@PathVariable String roleName) {
        try {
            List<User> users = rbacService.findUsersByRole(roleName);
            return CommonResponse.success(users);
        } catch (Exception e) {
            return CommonResponse.error("获取角色用户失败：" + e.getMessage());
        }
    }

    // 角色权限关联
    @PostMapping("/roles/{roleId}/permissions/{permissionId}")
    public CommonResponse<String> assignPermissionToRole(@PathVariable Long roleId, @PathVariable Long permissionId) {
        try {
            rbacService.assignPermissionToRole(roleId, permissionId);
            return CommonResponse.success("权限分配成功");
        } catch (Exception e) {
            return CommonResponse.error("分配权限失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/roles/{roleId}/permissions/{permissionId}")
    public CommonResponse<String> removePermissionFromRole(@PathVariable Long roleId, @PathVariable Long permissionId) {
        try {
            rbacService.removePermissionFromRole(roleId, permissionId);
            return CommonResponse.success("权限移除成功");
        } catch (Exception e) {
            return CommonResponse.error("移除权限失败：" + e.getMessage());
        }
    }

    @GetMapping("/roles/{roleId}/permissions")
    public CommonResponse<List<Permission>> getRolePermissions(@PathVariable Long roleId) {
        try {
            List<Permission> permissions = rbacService.getRolePermissions(roleId);
            return CommonResponse.success(permissions);
        } catch (Exception e) {
            return CommonResponse.error("获取角色权限失败：" + e.getMessage());
        }
    }
    
    // 超级管理员创建老师用户
    @SaCheckRole("super_admin")
    @PostMapping("/create-teacher")
    public CommonResponse<String> createTeacherUser(@RequestBody @Validated Map<String, String> request) {
        try {
            String username = request.get("username");
            String password = request.get("password");
            String email = request.get("email");
            String realname = request.get("realname");
            
            if (username == null || password == null || email == null || realname == null) {
                return CommonResponse.fail(400, "用户名、密码、邮箱和真实姓名不能为空");
            }
            
            Long adminId = StpUtil.getLoginIdAsLong();
            return rbacService.createTeacherUser(username, password, email, realname, adminId);
        } catch (Exception e) {
            return CommonResponse.error("创建老师用户失败：" + e.getMessage());
        }
    }
}
